// 全局请求封装
import config from './config.js'
const base_url = config.apiUrl

// 需要修改token，和根据实际修改请求头
export default (params) => {
	let api = params.url;
	let method = params.method || "get";
	let data = params.data || {};
	let header = {}
	if (undefined == params.header || undefined == params.header['Content-Type']) {
		header = {
			'Content-Type': 'application/json'
		};
	}else{
		header['Content-Type'] = params.header['Content-Type'];
	}
	// 获取本地token
	if (uni.getStorageSync("token")) {
		header['Authorization'] = uni.getStorageSync('token');
	}

	return new Promise((resolve, reject) => {
		// uni.showLoading({
		// 	title: '请求处理中',
		// 	mask: true
		// });
		uni.request({
			url: base_url + api,
			method: method,
			header: header,
			data: data,
			success(response) {
				if (response.statusCode == 200) {
					console.info(api, response)
					if(response.data.code === 401){
						uni.clearStorageSync()
						uni.navigateTo({
							url:"/pages/login/login"
						})
					}
					resolve(response.data);
				} else {
					//uni.clearStorageSync()
				}
			},
			fail(err) {
				console.log(err)
				if (err.errMsg.indexOf('request:fail') !== -1) {
					wx.showToast({
						title: '网络异常',
						icon: "error",
						duration: 2000
					})
				} else {
					wx.showToast({
						title: '未知异常',
						duration: 2000
					})
				}
				reject(err);

			},
			complete(resp) {
				// 不管成功还是失败都会执行
				//uni.hideLoading();
				//uni.hideToast();
				// console.info("333333",resp)
				// switch(api){
				//     case '/app/login':
				//         break;
				//     default:
				//         break;
				// }
			}
		});
	}).catch((e) => {});
};
